/**
 * Created by xinchunting on 17-9-21.
 */
var tableId;
var tableName;
var userId;
var iNotify = new iNotify({
    message: '有消息了。',//标题
    effect: 'flash', // flash | scroll 闪烁还是滚动
    openurl:"http://www.bing.com", // 点击弹窗打开连接地址
    onclick:function(){ //点击弹出的窗之行事件
        console.log("---")
    },
    //可选播放声音
    audio:{
        //可以使用数组传多种格式的声音文件
        file: ''
        //下面也是可以的哦
        //file: 'msg.mp4'
    },
    //标题闪烁，或者滚动速度
    interval: 1000,
    //可选，默认绿底白字的  Favicon
    updateFavicon:{
        // favicon 字体颜色
        textColor: "#fff",
        //背景颜色，设置背景颜色透明，将值设置为&ldquo;transparent&rdquo;
        backgroundColor: "#2F9A00"
    },
    //可选chrome浏览器通知，默认不填写就是下面的内容
    notification:{
        title:"通知！",//设置标题
        icon:"",//设置图标 icon 默认为 Favicon
        body:'您来了一条新消息'//设置消息内容
    }
});
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);  //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}
var stompClient = null;
var socket = new SockJS('/web-socket');
stompClient = Stomp.over(socket);
stompClient.connect('login', 'password', function (frame) {
    stompClient.subscribe('/topic/notify/call/' + getQueryString("id"), function (message) {
        console.log(message.body);
        console.log("1");
        var datas = JSON.parse(message.body);
        if (message.body.perd = 14) {
            var waitertableId="waiter"+datas.data.msgContent;
            $("."+waitertableId).css({
                "background":"#ED5046"
            })
        }
    });
    stompClient.subscribe('/topic/notify/serving/' + getQueryString("id"), function (message) {
        console.log(message.body);
        console.log("2");
        var datas = JSON.parse(message.body);
        if (datas.data.perd = 13) {
            $.ajax({
                url: "/api/admin/dc/queue/get",
                type: "GET",
                data: {userId: datas.data.fromUserId},
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    console.log(datas);
                    onTime(datas.data.msgContent, data.data[0].tableId)
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error("网络故障");
                }
            });
        }
    })
});
$("#onDish").click(function () {
    stompClient.send("/app/notify/serving/" + getQueryString("id") + "/" + $("input[id=userId]").val(), {header1: 'Header 1'}, JSON.stringify({
        companyId: getQueryString("id"),
        pred: 12,
        userId: $("input[id=userId]").val()
    }));
});
$("#logo").on("click",".waiter",function (e) {
    e.stopPropagation();
    $(this).css({
        "background":"#2ED183"
    })
});
function disconnect() {
    if (stompClient != null) {
        stompClient.disconnect();
    }
    console.log('Disconnected');
}

function onTime(time, tableId) {
    if (time == -1) {
        $("input[class=" + tableId + "]").val("立即上菜");
    } else {
        setInterval(function () {
            var t = time - Number(new Date());
            var m = Math.floor(t / 1000 / 60);
            var s = Math.floor(t / 1000 - m * 60);
            if (m < 10) {
                m = "0" + m;
            }
            if (s < 10) {
                s = "0" + s;
            }
            $("input[class=" + tableId + "]").val(m + ":" + s);
        }, 1000);
    }
}
$("#logo").on("click", ".dt", function () {
    tableId = $(this).data("id");
    tableName = $(this).data("name");
    console.log(tableId);
    console.log(tableName);
    console.log(name);
    $('#myModalLabel').html(tableName);
    $('#collapseOne').collapse('show');
    $('#collapseTwo').collapse('show');
    dishing(tableId);
    consoleData(tableId);
});
$(".btn-lg").click(function (e) {
    var num;
    if ($(e.target).attr("id") == "Y") {
        num = 1;
        iNotify.notify({
            title:"操作成功",
            body:"餐桌类型已经更改【使用】"
        });
        $("#"+tableId).css({
            "background":'url("http://static.ruitaowang.com/attached/file/2017/09/27/20170927110936233.jpg") 0 0 no-repeat',
            "background-size":"100%"
        })
    }
    if ($(e.target).attr("id") == "N") {
        num = 0;
        iNotify.notify({
            title:"操作成功",
            body:"餐桌类型已经更改【空闲】"
        });
        $("#"+tableId).css({
            "background":'url("http://static.ruitaowang.com/attached/file/2017/10/10/20171010135319987.jpg") 0 0 no-repeat',
            "background-size":"100%"
        })

    }
    console.log(num);
    $.ajax({
        url: "/api/admin/dc/table/consoleY",
        type: "PUT",
        data: {id: tableId, busy: num},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            toastr.success(data.msg, data.title);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error(errorThrown, textStatus);
        }
    });
});
function consoleData(id) {
    $.ajax({
        url: "/api/admin/dc/console/tableType/get",
        type: "GET",
        data: {id: id},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            var htmlQueue = "";
            console.log(data.data);
            if (!data.data) {
                $("#noQueue").show();
                $("#queue").hide();
            } else {
                $("#noQueue").hide();
                $("#queue").show();
                data.data.forEach(function (item) {
                    htmlQueue += "<tr><td>" + item.remark + "</td><td>" + item.num + "</td> <td>" + item.dayIndex + "</td> <td>" + item.day + "</td><td><button onclick='dishY(" + id + "," + item.id + ")'>确认用餐</button></td> </tr>"
                });
            }
            $("#tbody").html(htmlQueue);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
};
function dishing(id) {
    $.ajax({
        url: "/api/admin/dc/console/dishing/get",
        type: "GET",
        data: {id: id},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            console.log(data);
            if (!data.data) {
                $("#noDishingText").html(data.msg);
                $("#noDishing").show();
                $("#dishing").hide();
            } else {
                $("#noDishing").hide();
                $("#dishing").show();
                $("input[name=name]").val(data.data[0].remark);
                $("input[name=day]").val(data.data[0].day);
                $("input[name=num]").val(data.data[0].num);
                $("input[id=userId]").val(data.data[0].userId);
                userId = data.data[0].userId;
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
};
function dishY(id, queueId) {
    console.log("queueId:" + queueId);
    console.log("id:" + id);
    $.ajax({
        url: "/api/admin/dc/console/updateDish/get",
        type: "GET",
        data: {id: id, queueId: queueId, tableName: tableName},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            $.ajax({
                url:"/api/wx/message/template/send/dc/notify/hasTable",
                type:"GET",
                data:data.data[0],
                success:function (data, textStatus, jqXHR) {
                    if(data){
                        iNotify.notify({
                            title:"操作成功",
                            body:"已提醒客人就餐"
                        });
                    }
                }
            });
            $("input[name=name]").val(data.data[0].remark);
            $("input[name=day]").val(data.data[0].day);
            $("input[name=num]").val(data.data[0].num);
            dishing(id);
            consoleData(id);
            $('#collapseTwo').collapse('show');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
};
$().ready(function () {
    setInterval(function () {
        $.ajax({
            url: "/api/admin/dc/table/busy/get",
            type: "GET",
            data: {companyId:getQueryString("id")},
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                data.data.forEach(function (item) {
                    var thisBusy=$("#"+item.id).data("busy");
                    if(thisBusy != item.busy){
                        if (item.busy == 0){
                            $("#"+item.id).css({
                                "background":'url("http://static.ruitaowang.com/attached/file/2017/10/10/20171010135319987.jpg") 0 0 no-repeat',
                                "background-size":"100%"
                            })
                        }else if (item.busy == 1){
                            $("#"+item.id).css({
                                "background":'url("http://static.ruitaowang.com/attached/file/2017/09/27/20170927110936233.jpg") 0 0 no-repeat',
                                "background-size":"100%"
                            })
                        }
                    }
                });
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error("网络故障");
            }
        });
    }, 5000);
    $.ajax({
        url: "/api/admin/dc/table",
        type: "GET",
        data: {companyId: getQueryString("id"), page: 1, rows: 1000},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            data.data.forEach(function (item) {
                var waiterId="waiter"+item.id;
                $("#logo").append("<a data-toggle='modal' data-target='#myModal'><div class='col-md-2 dt' data-id='" + item.id + "' data-name='" + item.name + "' data-busy='"+item.busy+"'><div style='width:100%;;border-radius:50%;' class='thumbnail tableImg' id='"+item.id+"' data-busy='"+item.busy+"'><div style='color: #1E0FBE;' class='caption text-center'><h3><strong style='font-size:20px;'>" + item.name + "</strong></h3><h5>"+item.remark+"人桌</h5><h4><button type='button' class='waiter "+waiterId+"' style='border:0;font-size: 12px'>@服务员</button></h4><h4><input  class='" + item.id + "' style='border-radius:5px;font-size:12px ; width: 50px'></h4></div></div></div></a>");
                console.log(item.busy);
                if (item.busy == 0){
                    console.log("n");
               $("#"+item.id).css({
                   "background":'url("http://static.ruitaowang.com/attached/file/2017/10/10/20171010135319987.jpg") 0 0 no-repeat',
                   "background-size":"100%"
               })
                }else if (item.busy == 1){
                    console.log("Y");
                    $("#"+item.id).css({
                        "background":'url("http://static.ruitaowang.com/attached/file/2017/09/27/20170927110936233.jpg") 0 0 no-repeat',
                        "background-size":"100%"
                    })
                }
            });
            $("#logo").append("<div class='col-md-2'><a onclick='skipToUpdate()'><div style='width:100%;border: 0px' class='thumbnail'><br><br><div class='caption text-center'><h3><strong style='font-size:20px;color:#2095f2'>加桌</strong></h3></div></div></a></div>");
            $(".thumbnail").height($(".thumbnail").width());
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
    $.ajax({
        url: "/api/admin/dc/console/QueueTime/get",
        type: "GET",
        data: {companyId: getQueryString("id")},
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            data.data.forEach(function (item) {

            });
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
});

function skipToUpdate() {
    layer.open({
        title: ["加桌管理", "font-size:20px;"],
        type: 2,
        scrollbar: false,
        shadeClose: true,
        shade: 0.8,
        area: ['100%', '100%'],
        content: "/web/dc_table_create.html?id=" + getQueryString("id")
    })
}
function tableUpdate() {
    layer.open({
        title: ["修改加桌管理", "font-size:20px;"],
        type: 2,
        scrollbar: false,
        shadeClose: true,
        shade: 0.8,
        area: ['100%', '100%'],
        content: "/admin/dinner/table/update/get/" + tableId
    })
}